'use strict';

const Controller = require('egg').Controller;

class AdminController extends Controller {
    async index() {
        const { ctx } = this;
        ctx.body = 'hi, egg';
    }

    //判断用户名密码是否正确
    async checkLogin() {
        let { userName, passWord } = this.ctx.request.body;
        console.log(userName,passWord)
        const sql = `SELECT userName FROM user WHERE userName = '${userName}' AND passWord = '${passWord}'`
        console.log(sql)
        const res = await this.app.mysql.query(sql)
        if (res.length > 0) {
            this.ctx.body = {
                'data': '登录成功',
                result: true,
                data:res,
                code: '200',
            }
        } else {
            this.ctx.body = {
                result: false,
                data: '登录失败'
            }
        }
    }
    //添加文章
    async addArticle() {
        let addArticle = this.ctx.request.body
        console.log(addArticle)
        const result = await this.app.mysql.insert('article', addArticle)
        const insertSuccess = result.affectedRows === 1
        const article_id = result.article_id
        console.log(insertSuccess)
        this.ctx.body = {
            result: true,
            code: '200',
            isSuccess: insertSuccess,
            article_id: article_id
        }
    }
    //修改文章
    async updateArticle() {
        let { content, introduce, title, type_id, article_id } = this.ctx.request.body;
        let sql = `UPDATE article SET content='${content}',introduce='${introduce}',title='${title}',type_id=${type_id} WHERE article_id =${article_id}`;

        const result = await this.app.mysql.query(sql)
        const updateSuccess = result.affectedRows === 1
        console.log(updateSuccess)

        this.ctx.body = {
            msg: '修改成功',
            result: true,
            code: '200',
            isSuccess: updateSuccess
        }
    }

    //删除文章
    async delArticle() {
        let article_id = this.ctx.params.article_id
        console.log(article_id)
        const res = await this.app.mysql.delete('article', { 'article_id': article_id })
        console.log(res)
        this.ctx.body = {
            code: '200',
            result: true,
            msg: '删除成功',
            data: res
        }
    }

    //删除留言
    async delMsg() {
        let email = this.ctx.params.email
        const res = await this.app.mysql.delete('message', { 'email': email })
        this.ctx.body = {
            code: '200',
            result: true,
            msg: '删除成功',
            data: res
        }
    }
}

module.exports = AdminController;
